package com.cn.kehong.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cn.kehong.conf.Config;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @类名:SubscribeSample
 * @包名:com.cn.kehong.service
 * @作者:chenxingliang
 * @时间:2022-12-05 13:57
 * @版本:1.0.0
 */

//@EnableScheduling
//@Component
public class SubscribeSample {


    @Autowired
    private Config config;

    private MqttClient refoClient;

    @Autowired
    RedisTemplate redisTemplate;



    @Scheduled(cron = "*/10 * * * * ?")
    public void buildSubscribe() throws MqttException {
        System.out.println("=======buildSubscribe=========");
        try {
            if (refoClient != null) {
                return;
            }
            // host为主机名，test为clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
            refoClient = new MqttClient(config.mqttHost, "refo2", new MemoryPersistence());
            // MQTT的连接设置
            MqttConnectOptions options = new MqttConnectOptions();
            // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(true);
            // 设置连接的用户名
            options.setUserName(config.mqttUserName);
            // 设置连接的密码
            options.setPassword(config.mqttPassWord.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            // 设置回调函数
            refoClient.setCallback(new MqttCallback() {

                @Override
                public void connectionLost(Throwable cause) {
                    refoClient = null;
                    System.out.println("refoClient connectionLost");
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    System.out.println("topic:" + topic);
                    System.out.println("Qos:" + message.getQos());
                    final String acceptMessage = new String(message.getPayload(), "UTF-8");
                    Runnable runnable = new Runnable() {
                        @Override
                        public void run() {
                            if (!StringUtils.equals("close", acceptMessage)) {
                                try {
                                    System.out.println(acceptMessage);
                                    JSONObject jsonObject = JSON.parseObject(acceptMessage);
//                                    meterPowerService.addMeterPower(jsonObject);

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    };
                    Thread thread = new Thread(runnable);
                    thread.setDaemon(true);
                    thread.start();
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    System.out.println("=========deliveryComplete=========");
                }

            });
            refoClient.connect(options);
            //订阅消息
            refoClient.subscribe("refo",2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
